package org.jsola.hr.web;

import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.ImportIncreaseDTO;
import org.jsola.hr.dto.SaleServerCostRecordAddDTO;
import org.jsola.hr.dto.SaleServerCostRecordImportDTO;
import org.jsola.hr.dto.SaleServerCostRecordUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.SaleServerCostRecordQuery;
import org.jsola.hr.service.ISaleServerCostRecordService;
import org.jsola.hr.vo.ImportExcelResultListVO;
import org.jsola.hr.vo.SaleServerCostRecordListVO;
import org.jsola.hr.vo.SaleServerCostRecordVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import javax.validation.Valid;


/**
 * 客户服务费记录
 *
 * @author zhr
 */
@RestController("hrSaleServerCostRecordController")
@RequestMapping(HrConstants.API_PATH + "/v1/saleServerCostRecords")
public class SaleServerCostRecordController implements ISaleServerCostRecordControllerAPI {

    @Autowired
    private ISaleServerCostRecordService saleServerCostRecordService;

    @Override
    @PostMapping
    public Result<SaleServerCostRecordVO> save(@Valid @RequestBody SaleServerCostRecordAddDTO saleServerCostRecordAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增客户服务费记录权限校验

        return Result.success(
                saleServerCostRecordService.save(saleServerCostRecordAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody SaleServerCostRecordUpdateDTO saleServerCostRecordUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改客户服务费记录权限校验

        int count = saleServerCostRecordService.update(saleServerCostRecordUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{saleServerCostRecordId}")
    public Result<Integer> delete(@PathVariable String saleServerCostRecordId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除客户服务费记录权限校验

        int count = saleServerCostRecordService.deleteByIds(tokenUser, saleServerCostRecordId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] saleServerCostRecordIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除客户服务费记录权限校验

        int count = saleServerCostRecordService.deleteByIds(tokenUser, saleServerCostRecordIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{saleServerCostRecordId}")
    public Result<SaleServerCostRecordVO> findById(@PathVariable String saleServerCostRecordId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看客户服务费记录权限校验

        return Result.success(
                saleServerCostRecordService.selectById(saleServerCostRecordId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<SaleServerCostRecordListVO>> listAll(@Valid SaleServerCostRecordQuery saleServerCostRecordQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看客户服务费记录权限校验

        return Result.success(
                saleServerCostRecordService.select(saleServerCostRecordQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<SaleServerCostRecordListVO>> page(@Valid SaleServerCostRecordQuery saleServerCostRecordQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleServerCostRecordService.selectPage(saleServerCostRecordQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/import")
    public Result<ImportExcelResultListVO<SaleServerCostRecordImportDTO>> importIncrease
            (@RequestParam("file") MultipartFile file) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                saleServerCostRecordService.importFile(excelFile, tokenUser)
        );
    }

    @Override
    @PutMapping("/overlaidData")
    public Result<String> overlaidData(@RequestBody List<SaleServerCostRecordImportDTO> importData) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        saleServerCostRecordService.overlaidData(importData, tokenUser);
        return Result.success();
    }

    @Override
    @PostMapping("/exportErrorList")
    public ResponseEntity<Resource> exportErrorList
            (@RequestBody ImportExcelResultListVO<SaleServerCostRecordImportDTO> errorList) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // todo 导出账单权限校验
        String excelFilePath = saleServerCostRecordService.exportErrorList(errorList);
        // 编码文件名，防止乱码
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

}

